using SimpleJSON;
using UnityEngine;
using UnityEngine.UI;

namespace Gj
{
    public class NumberHelper : NodeHelper
    {
        public Color disableColor = new(255, 255, 255, 0.4f);
        public Color originColor = new(255, 255, 255);
        public string placeholder;
        public int min;
        public int max;

        [SelectRef(UIKey.DATA_KEY)] public SelectKey disabledKey;
        private int _i;
        private Text _Text;
        protected bool disabled;

        private Text Text
        {
            get
            {
                if (_Text == null) _Text = GetComponent<Text>();
                return _Text;
            }
        }

        protected override BindDataType bindDataType => BindDataType.Int;

        public override void SetData(JSONObject json)
        {
            if (!disabledKey.IsEmpty())
            {
                disabled = disabledKey.Get(json).AsBool;
                if (disabled)
                    Text.color = disableColor;
                else
                    Text.color = originColor;
            }

            base.SetData(json);
        }

        protected override void BindData(int i)
        {
            if (i == null) i = 0;
            if (_i == i) return;
            _i = i;
            UpdateText(_i);
        }

        private void UpdateText(int i)
        {
            var text = i.ToString();

            if (min != 0 && i < min)
                text = placeholder;
            else if (max != 0 && i > max) text = string.Format("{0}+", max);
            Text.text = text;
        }

        public void Disabled()
        {
            disabled = true;
            Text.color = disableColor;
        }

        public void Enabled()
        {
            disabled = false;
            Text.color = originColor;
        }
    }
}